package com.kgis.kp.dao.dialect;

import com.kgis.kp.common.util.Assertion;
import com.kgis.kp.common.vo.Ordering;

/**
 * @see also org.hibernate.dialect.Oracle9iDialect
 * 
 * @author zhxiaomiao
 * 
 * 
 */
public class OracleJdbcTemplateDialect extends AbstractJdbcTemplateDialect {

	public String sequenceStatement(String sequenceName) {
		Assertion.notEmpty(sequenceName, "sequenceName not found");

		StringBuilder statement = new StringBuilder("select ");
		statement.append(sequenceName);
		statement.append(".nextval from dual");
		return statement.toString();
	}

	public String countStatement(String namedStatement) {
		Assertion.notEmpty(namedStatement, "namedStatement not found");

		int index = namedStatement.toLowerCase().indexOf("from");

		if (index < 0) {
			throw new IllegalArgumentException("no 'from' clause found");
		}
		StringBuilder statement = new StringBuilder("select count(1) ");
		if (namedStatement.toLowerCase().indexOf("from", index + 1) > index)
			statement.append(" from (").append(namedStatement).append(" )");
		else
			statement.append(namedStatement.substring(index, namedStatement.length()));

		return statement.toString();

	}

	public String paginationStatement(String namedStatement, int _skipResult, int _maxResult) {
		namedStatement = namedStatement.trim();

		StringBuilder statement = new StringBuilder(namedStatement.length() + 100);

		if (_skipResult > 0 || _maxResult > 0) {
			statement.append("select * from ( ");

			if (_skipResult > 0) {
				statement.append(" select row_.*, rownum rownum_ from ( ");
			}

			statement.append(namedStatement);

			if (_skipResult > 0) {
				statement.append(" ) row_ ) where rownum_ <= :").append(MAX_RESULTS).append(" and rownum_ > :").append(SKIP_RESULTS);
			} else {
				statement.append(" ) where rownum <= :").append(MAX_RESULTS);
			}

			return statement.toString();
		} else {
			return namedStatement;
		}
	}

	public String appendOrderBy(String namedStatement, Ordering ordering) {
		if (null != ordering && notEmpty(ordering.orderClause())) {
			// Order by 的column不可以作为动态参数传入
			namedStatement = namedStatement + " order by " + ordering.orderClause();
		}
		return namedStatement;
	}

}
